<template>
  <div style="width:400px;">
    <ocean :use="form"></ocean>
  </div>
</template>
<script lang="tsx" setup>
import { useForm } from '@/ocean';
import { ref } from 'vue';
import { EnterpriseAPI, GlobalAPI } from '@/app/api';
import { NUpload } from 'naive-ui';

type Model = {
  enterpriseAddress: string,
  enterpriseName: string,
  enterprisePhone: string,
  enterpriseType: string,
  discount: number,
  subsidy: number,
  logo: string,
}

let props = defineProps<{
  row?: Model,
}>()

let isEdit = !!props.row;

const { action, headers } = GlobalAPI.uploadFile();

const onFinish = (e) => {
  const res = JSON.parse(e.event.target.response);
  form.model.logo = res.data;
}



const fileList = ref([]);

let form = useForm<Model>();
form.item('企业名称', 'enterpriseName').input();
form.item('企业类型', 'enterpriseType').select({ options: [{ label: '开放型', value: 'K' }, { label: '福利型', value: 'F' }] })
form.item('联系方式', 'enterprisePhone').input();
form.item('企业地址', 'enterpriseAddress').input();
form.item('企业折扣（%）', 'discount').inputNumber();
form.item('企业补贴（元）', 'subsidy').inputNumber();
form.item('上传logo图片', 'logo').define(() => <NUpload
  action={action}
  headers={headers}
  listType="image-card"
  default-file-list={fileList}
  max={1}
  accept="image/*"
  on-finish={(e) => onFinish(e)}
></NUpload>)

let submitAPI = EnterpriseAPI.addEnterprise;

if (isEdit) {
  submitAPI = EnterpriseAPI.updateEnterprise;
  form.setModel({ ...props.row, discount: props.row.discount * 100 });
  if (props.row.logo) {
    fileList.value = [{
      status: 'finished',
      url: props.row.logo,
    }]
  }
}

const submit = () => {
  return submitAPI({
    ...form.model,
    discount: form.model.discount / 100
  });
}

defineExpose({ submit });
</script>